import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;

import Interfaces.ICommandChannelListener;
import Interfaces.ICommandsHandler;
import Messages.CommandMessage;
import Messages.CommandTypeEnum;


public class CommandChannelListener extends Thread implements ICommandChannelListener
{
	private boolean m_isListening;
	private ICommandsHandler m_commandHandler;
	private ServerSocket m_socket;
	
	public CommandChannelListener(int port, ICommandsHandler handler) throws IOException
	{
		m_isListening = false;
		m_socket = new ServerSocket(port);
		m_commandHandler = handler;
	}
	
	public void stopListening()
	{
		m_isListening = false;
	}
	
	public void startListening()
	{
		m_isListening = true;
		start();
	}

	@Override
	public void run()
	{
		while(m_isListening)
		{
			try 
			{
				Socket socket = m_socket.accept();
				ObjectInputStream is = new ObjectInputStream(socket.getInputStream());
				CommandMessage message = (CommandMessage)is.readObject();
				if(message.Type == CommandTypeEnum.Register)
				{
					m_commandHandler.HandleRegisterCommand(message.MonitorIP, message.MonitorDataPort,message.MonitorDataType, message.Parameters);
				}
				else if (message.Type == CommandTypeEnum.Unregister)
				{
					m_commandHandler.HandleUnregisterCommand(message.MonitorIP, message.MonitorDataPort, message.MonitorDataType, message.Parameters);
				}				
			} 
			catch (IOException e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
			catch (ClassNotFoundException e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		try 
		{
			m_socket.close();
		} 
		catch (IOException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
